
import Foundation

//栈可以解决十进制转为二进制的问题、任意进制转换的问题、平衡园括号问题、汉罗塔问题。
struct Stack<T: CustomStringConvertible>: CustomStringConvertible {
    
    
    private var stack = Array<T>() //这里用数组实现最为简单(扩容交给数组去做) ， 也可以用双向链表， 单链表每次push都插入在first前面 然后first就是栈顶元素了
     
    var count: Int {
        get {
            return stack.count
        }
    }
    
    func isEmpty() -> Bool {
        return stack.isEmpty
    }
    
    mutating func push(element: T) {
        stack.append(element)
    }
    
    mutating func pop() -> T? {
        if stack.count > 0 {
            return stack.removeLast()
        }
        return nil
    }
    
    func peek() -> T? {//窥探栈顶元素  不改变栈
        if stack.count > 0 {
            return stack[stack.count - 1]
        }
        return nil
    }
    
    var description: String {
        get {
            var str = "stack bottom->\n"
            self.stack.forEach { item in
                str.append(item.description + " ")
            }
            return str
        }
    }
    
}

extension Stack {
    static func testStack() {
        var stack = Stack<Int>()
        stack.push(element: 1)
        stack.push(element: 2)
        stack.push(element: 3)
        stack.push(element: 4)
        
        
        print(stack.isEmpty())
        print(stack.count)
        
        print(stack)
        
        
    }
}
